<template>
    <section>
        <!--高级查询工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.name" placeholder="部门名称"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="flushDepartments">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
                  style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="60">
            </el-table-column>
            <el-table-column prop="name" label="部门名称" width="120">
            </el-table-column>
            <el-table-column prop="sn" label="标识" width="120">
            </el-table-column>
            <el-table-column prop="dirPath" label="路径" width="120">
            </el-table-column>
            <el-table-column prop="state" label="状态" width="100">
                <template scope="scope">
                    <span v-if="scope.row.state === 0" style="color: #11b95c">启用</span>
                    <span v-else-if="scope.row.state === -1" style="color: red">禁用</span>
                    <span v-else style="color: #8c939d">未知</span>
                </template>
            </el-table-column>
            <el-table-column prop="manager.username" label="部门经理" width="100">
            </el-table-column>
            <el-table-column prop="parent.name" label="上级部门">
            </el-table-column>
            <el-table-column label="操作" width="300">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--分页条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                           :page-size="pageSize"
                           :total="total"
                           :current-page="currentPage"
                           style="float:right;">
            </el-pagination>
        </el-col>

        <!--新增界面-->
        <el-dialog :title="title" :visible.sync="addFormVisible" :close-on-click-modal="false">
            <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
                <el-form-item label="部门名称" prop="name">
                    <el-input v-model="addForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="addForm.state">
                        <el-radio class="radio" :label="0">启用</el-radio>
                        <el-radio class="radio" :label="-1">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="部门编号">
                    <el-input v-model="addForm.sn"></el-input>
                </el-form-item>
                <el-form-item label="部门经理">
                    <el-select v-model="addForm.manager" value-key="id" placeholder="请选择">
                        <el-option
                                v-for="item in emps"
                                :key="item.id"
                                :label="item.username"
                                :value="item">
                            <span style="float: left">{{ item.username }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="上级部门">
                    <div class="block">
                        <!--可通过 props.checkStrictly = true 来设置父子节点取消选中关联，从而达到选择任意一级选项的目的。-->
                        <!--:label 是用来显示的-->
                        <!--:value="id" 用来传值得-->
                        <el-cascader
                                v-model="addForm.parent"
                                :options="depts"
                                :props="{ checkStrictly: true, label:'name', value:'id' }"
                                clearable></el-cascader>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>

    </section>
</template>

<script>
    import util from '../../common/js/util'
    //import NProgress from 'nprogress'
    import {
        getDepartmentListPage,
        removeDepartment,
        batchRemoveDepartment,
        editDepartment,
        addDepartment
    } from '../../api/api';

    export default {
        data() {
            return {
                depts:[],
                emps:[],
                filters: {
                    name: ''
                },
                departments: [],
                total: 0,
                currentPage: 1,
                pageSize: 5,
                listLoading: false,
                sels: [],//列表选中列
                title:'新增',

                addFormVisible:false,// 新增模态框是否显示
                addLoading:false,
                addFormRules:{// 验证规则
                    name:[
                        {required:true, message:'请输入名称', trigger:'blur'}
                    ]
                },
                addForm:{// 初始化新增界面数据
                    id:null,
                    name:'',
                    sn:'',
                    state:0,
                    manager:null,
                    parent:null
                }

            }
        },
        methods: {
            handleCurrentChange(page) {
                this.currentPage = page;
                this.getDepartments();
            },
            //获取部门列表
            getDepartments() {
                let para = {
                    currentPage: this.currentPage,
                    pageSize: this.pageSize,
                    keyword: this.filters.name
                };
                this.listLoading = true;
                //NProgress.start();
                this.$http.post("/dept", para).then(res => {
                    this.total = res.data.total;
                    this.departments = res.data.rows;
                    this.listLoading = false;
                    //NProgress.done();
                });
            },
            //刷新部门列表（跳转回第一页）
            flushDepartments() {
                let para = {
                    currentPage: 1,
                    pageSize: this.pageSize,
                    keyword: this.filters.name
                };
                this.currentPage = para.currentPage;
                this.listLoading = true;
                //NProgress.start();
                this.$http.post("/dept", para).then((res) => {
                    this.total = res.data.total;
                    this.departments = res.data.rows;
                    this.listLoading = false;
                    //NProgress.done();
                });
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该数据吗?', '提示', {
                    type:'warning'
                }).then(()=>{
                    this.listLoading = true;
                    this.$http.delete('/dept/' + row.id).then(res=>{
                        if(res.data.success){
                            this.$message({
                                message:res.data.msg,
                                type:'success'
                            })
                        }else{
                            this.$message({
                                message:res.data.msg,
                                type:'error'
                            })
                        }
                        this.getDepts();
                        this.getDepartments();
                        this.listLoading = false;
                    })
                })
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.getDepts();
                this.title = '编辑';
                this.addFormVisible = true;
                // 回显数据
                let para = Object.assign(this.addForm, row);
                // 上级部门回显的调整
                if(row.parent){
                    let arr = row.dirPath.split("/");
                    para.parent = arr.slice(1, arr.length - 1).map(Number);
                }
            },
            //显示新增界面
            handleAdd: function () {
                this.getDepts();
                this.title = '新增';
                // 清空表单数据
                this.addForm = {
                    id:null,
                    name:'',
                    sn:'',
                    state:0,
                    manager:null,
                    parent:null
                }
                this.addFormVisible = true;
            },
            //新增
            addSubmit: function () {
                // 验证规则
                this.$refs.addForm.validate((valid) =>{
                    if (valid){// 通过验证
                        this.$confirm('确认提交该数据吗?', '提示', {}).then(() =>{
                            this.addLoading = true;
                            // 获取当前表单数据
                            let param = Object.assign({}, this.addForm);
                            if(param.parent != null){
                                let ids = param.parent;
                                param.parent = {
                                    id:ids[ids.length - 1]
                                }
                            }
                            // 提交表单
                            this.$http.put("/dept", param).then(res =>{
                                if(res.data.success){
                                    this.$message({
                                        message:res.data.msg,
                                        type:'success'
                                    })
                                    this.getDepartments();
                                }else{
                                    this.$message({
                                        message:res.data.msg,
                                        type:'error'
                                    })
                                }
                                this.getDepts();
                                this.addFormVisible = false;
                                this.addLoading = false;
                            })
                        })
                    }
                })
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                let ids = this.sels.map(item => item.id);
                this.$confirm('确认删除该数据吗?', '提示', {
                    type:'warning'
                }).then(()=>{
                    this.$http.patch("/dept", ids).then(res=>{
                        if(res.data.success){
                            this.$message({
                                message:res.data.msg,
                                type:'success'
                            })
                        }else{
                            this.$message({
                                message:res.data.msg,
                                type:'error'
                            })
                        }
                        this.getDepartments();
                    })
                })
            },
            getEmps: function(){
                this.$http.get("/emp").then(res => {
                    this.emps = res.data;
                })
            },
            getDepts: function(){
                this.$http.get("/dept/getTree").then(res => {
                    this.depts = this.getDeptsData(res.data);
                })
            },
            // 处理获取到的部门树数据
            getDeptsData(data){
                for(let i; i < data.length; i++){
                    if (data[i].children.length < 1){// children为空数组，则将children设为undefined
                        data[i].children = undefined;
                    }else {// children不为空数组，则继续递归调用此方法
                        this.getDeptsData(data[i].children);
                    }
                }
                return data;
            }
        },
        mounted() {
            this.getDepartments();
            this.getEmps();
        }
    }

</script>

<style scoped>

</style>